<template>
  <div class="center-container center">
    <el-row class="login-container" justify="center" :align="'middle'">
      <el-card style="max-width: 480px">
        <template #header>
          <div class="car-header center">
            <img class="adaptive-image" :src="imgUrl" alt="">
          </div>
        </template>
        <div class="jump-Link">
          <el-link class="jump-Link-right" type="primary" @click="handleChange">{{ formType ? '返回登录' : '注册账号'
          }}</el-link>
          <div class="center">
            <el-form ref="loginFormRef" :model="loginForm" label-width="auto" style="max-width: 600px;"
              class="demo-ruleForm" :rules="rules">
              <el-form-item prop="userName">
                <el-input v-model="loginForm.userName" style="width: 240px" placeholder="手机号" clearable
                  prefix-icon="User" />
              </el-form-item>

              <el-form-item prop="passWord">
                <el-input v-model="loginForm.passWord" style="width: 240px" type="password" placeholder="密码"
                  show-password clearable prefix-icon="Lock" />
              </el-form-item>

              <el-form-item v-if="formType" prop="validCode">
                <el-input v-model="loginForm.validCode" style="max-width: 240px" placeholder="验证码" prefix-icon="Lock">
                  <template #append>
                    <span @click="countDownChange">{{ countDown.validText }}</span>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="">
                <el-button class="ti-jiao" :style="{ width: '100%' }" @click="submitForm(loginFormRef)">
                  {{ formType ? '注册账号' : '登录' }}
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive , computed ,toRaw } from 'vue'
import { ElMessage } from 'element-plus'
import { getCode, userAuthentication, getLogin , menuPermissions } from '@/api/index'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
const imgUrl = new URL('/login-head.png', import.meta.url).href

const router = useRouter()
// 切换表单 （0登录页面显示注册 1注册页面子显示登录）
const formType = ref(0)



// 点击切换登录和注册
const handleChange = () => {
  formType.value = formType.value ? 0 : 1
}

// 表单数据
const loginForm = reactive({
  userName: '',
  passWord: '',
  validCode: '',
})




// 验证码倒计时
const countDown = reactive({
  validText: '获取验证码',
  time: 60
})
// 做出限制，不能让他重复多次点击造成数据错乱
let flag = false

// 获取验证码
const countDownChange = (() => {

  // 如果已发送不处理
  if (flag) return
  // 判断手机号是否合法
  const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
  // /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
  if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
    return ElMessage({
      message: '请检查手机号是否正确',
      type: 'warning',
    })
  }
  flag = true
  // 倒计时 先写
  let time = setInterval(() => {
    if (countDown.time <= 0) {
      countDown.time = 60;
      countDown.validText = `获取验证码`;
      flag = false;
      clearInterval(time); // 清除定时器
    } else {
      countDown.time -= 1;
      countDown.validText = `剩余${countDown.time}s后`;
    }
  }, 1000)

  // 获取验证码
  getCode({ tel: loginForm.userName }).then(({ data }) => {
    console.log(data, 'data')
    if (data.code === 200) {
      // ElMessage({
      //   message: '验证码已发送',
      //   type: 'success',
      // }) 
      ElMessage.success('验证码已发送')
    }
  })

  /*
  setInterval(() => {
    if (countDown.time <= 0) {
      clearInterval(time); // 清除定时器
      countDown.time = 6
      countDown.validText = '获取验证码'
      flag = false
    } else {
      countDown.time -= 1
      countDown.validText = `${countDown.time}s后重试`
      
    }

  }, 1000)

  flag = true
  */

})
// 账号校验规则
const validateUser = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else {
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    phoneReg.test(value) ? callback() : callback(new Error('请输入正确的手机号'))
  }
}

// 密码校验规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    const reg = /^[a-zA-Z0-9]{4,16}$/
    reg.test(value) ? callback() : callback(new Error('密码格式不正确，需要6到16位字符，请确认格式'))
  }

}
// 
// 表单校验
const rules = reactive({
  userName: [{ validator: validateUser, trigger: 'blur' }],
  passWord: [{ validator: validatePass, trigger: 'blur' }],
})


const routerList = computed(() => store.state.menu.routerList)
const loginFormRef = ref()
const store = useStore()
// 表单提交
const submitForm = async (formEl) => {
  if (!formEl) return
  try {
    // 手动触发校验，返回一个 Promise
    const valid = await formEl.validate();
    if (valid) {
      console.log(loginForm, 'submit!');
      // 调整字段名
      const requestData = {
        userName: loginForm.userName,
        passWord: loginForm.passWord, 
        validCode: loginForm.validCode
      };
      if (formType.value) {
        // 注册页面
        try {
          console.log('请求参数:', requestData);
          const response = await userAuthentication(loginForm);
          const { data } = response;
          console.log('响应状态码:', response.status);
          console.log('响应头:', response.headers);
          console.log('响应数据:', data);
          if (data.code === 10000) {
            ElMessage.success('注册成功,请登录');
            formType.value = 0;
          }
        } catch (error) {
          console.error('请求失败:', error);
          ElMessage.error('请求失败，请稍后重试');
        }
      } else {
        // 登录页面
        try {
          const response = await getLogin(loginForm);
          const { data } = response;
          if (data.code === 10000) {
            ElMessage.success('登录成功');
            console.log(data, 'data');
            // 将token和用户信息缓存到浏览器
            localStorage.setItem('pz_token', data.data.token);
            localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo));
            menuPermissions().then(({ data }) => {
              console.log(data, 'menuPermissions 用户菜单权限');
              store.commit('dynamicMenu', data.data)
              console.log(routerList,'routerList---');
              toRaw(routerList.value).forEach(item => {
                router.addRoute('main',item)
              })
              router.push('/')
            })
            // 跳转到首页
            // router.push('/');
          }
        } catch (error) {
          console.error('登录请求失败:', error);
          ElMessage.error('登录请求失败，请稍后重试');
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  } catch (error) {
    console.error('表单验证出错:', error);
  }
};


</script>

<style scoped lang="less">
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.center-container {
  min-height: 100vh;

  .login-container {
    .car-header {
      width: 240px;
      height: 100%;
      background-color: #899fe1;

      /* 图片自适应样式 */
      .adaptive-image {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
      }
    }

    .jump-Link {
      text-align: right;
      margin-bottom: 10px;

      .jump-Link-right {
        margin-bottom: 10px;
      }
    }

    .ti-jiao {
      width: 240px;
      background-color: rgb(64, 158, 255);
      color: white;
    }

    .ti-jiao:active {

      background-color: rgb(98, 106, 239);
    }
  }
}






/*
:deep(.el-card__header) {
    padding: 0
  }
  .login-container {
    height: 100%;
    .card-header{
      background-color: #899fe1;
      img {
        width: 430px;
      }
    }
    .jump-link {
      text-align: right;
      margin-bottom: 10px;
    }
  }
*/
</style>